package com.dxysun.netty.client;

import com.dxysun.netty.server.SampleInBoundHandler;
import com.dxysun.netty.server.SampleOutBoundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpVersion;

import java.net.URI;
import java.nio.charset.StandardCharsets;

public class Client
{

	public void connect(String host, int port) throws Exception
	{
		EventLoopGroup group = new NioEventLoopGroup();
		try
		{
			Bootstrap b = new Bootstrap();
			b.group(group);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch)
				{
					ch.pipeline().addLast(new SampleInBoundHandler("SampleInBoundHandlerA", false))
							.addLast(new SampleInBoundHandler("SampleInBoundHandlerB", false))
							.addLast(new SampleInBoundHandler("SampleInBoundHandlerC", true));
					ch.pipeline().addLast(new SampleOutBoundHandler("SampleOutBoundHandlerA"))
							.addLast(new SampleOutBoundHandler("SampleOutBoundHandlerB"))
							.addLast(new SampleOutBoundHandler("SampleOutBoundHandlerC"));
				}
			});
			ChannelFuture f = b.connect(host, port).sync();
			URI uri = new URI("http://127.0.0.1:8088");
			String content = "hello world";

			f.channel().write(content);
			f.channel().flush();
			f.channel().closeFuture().sync();
		}
		finally
		{
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception
	{
		Client client = new Client();
		client.connect("127.0.0.1", 8088);
	}
}
